import React from 'react'
import { Link, Toast, Input, Button, Checkbox } from '../ui-components'
import style from './style'
import { connect } from 'react-redux'
import cookie from 'component-cookie'
import store from 'yields-store'

const { success, error } = Toast

@connect((auth) => ({auth}))
class Signup extends React.Component {

	lock=false

	state= {
		signLabel: '注册'
	}

	handleRememberMe() {
		this.setState({
			rememberMe: this.state.rememberMe === 1? 0: 1
		})
	}

	handleInput(name) {
		return (value) => {
			this.setState({
				[name]: value
			})
		}
	}

	validate(els) {
		return els.every(el => !el.state.error && el.state.value)
	}

	handleLogin() {
		if (this.lock) return
		if (this.validate([this.refs.email, this.refs.password])) {
			this.props.login(this.state)
		}
	}

	componentWillReceiveProps(props) {
		const { code='', msg, data={} } = props.auth.login
		// 200xx
		if(('' + code).match(/200\d+/)) {
			if (data.accessToken) {
				this.lock = true
				this.setState({
					loginLabel: '跳转中...'
				})
				for(let i in data) {
					store(i, data[i])
				}
				location.href = '/'
			}
		} else {
			if (msg) {
				error(msg)
			}
		}
	}

	render() {
		return (
			<div className={style.login}>
				<h1>注册</h1>
				<Input 
					autoFocus
					onChange={::this.handleInput('email')} 
					className={style.input} 
					label="公司名称"/>
				<Input 
					onChange={::this.handleInput('password')} 
					className={style.input} 
					label="手机号"/>
				<Input 
					onChange={::this.handleInput('password')} 
					className={style.input} 
					name="email"
					label="邮箱"/>
				<Input 
					onChange={::this.handleInput('password')} 
					className={style.input} 
					type="password"
					label="密码"/>
				<Button 
					onClick={::this.handleLogin}
					className={style.button} label={this.state.signLabel}/>
				<Link _ to='#/login' className={style.signUp}>已有帐号，立即登录</Link>
			</div>
		)
	}
}

export default Signup
